<?php

/* all functions in this file uses the Systems hungarian notation for defining
 * variables,function parameters and function names
 */

/* bLogin is resposible for accessing the mySql database, retreiving password 
 * data and checking against the username $sUser, if the user is found and the 
 * password is correct the function returns true, otherwise it returns false;
 */

if (!function_exists('bLogin'))
{

    function bLogin($sUser, $sPass)
    {
        $sqlConn = sqlConnect();
        if ($sqlConn == null)
            return false;
        else
        {
            $sQuery = "SELECT * FROM basic WHERE UserName='{$sUser}'";
            $rsResult = mysql_query($sQuery, $sqlConn);
            if (!$rsResult)
            {
                die("unable to retreive result set" . mysql_error());
            }
            else
            {
                $iRows = mysql_num_rows($rsResult);
                if ($iRows === 0)
                {
                    mysql_close($sqlConn);
                    return false;
                }
                else
                {
                    $sQuery = "SELECT * FROM basic WHERE UserName='{$sUser}' AND PassWord='{$sPass}'";
                    $rsResult = mysql_query($sQuery, $sqlConn);
                    if (!$rsResult)
                    {
                        die("unable to retreive result set" . mysql_error());
                    }
                    else
                    {
                        $iRows = mysql_num_rows($rsResult);
                        if ($iRows === 0)
                        {
                            mysql_close($sqlConn);
                            return false;
                        }
                        else
                        {
                            mysql_close($sqlConn);
                            return true;
                        }
                    }
                }
            }
        }
    }

}

/* bRegister is responsible for contacting the mySql database and entering the 
 * data for a new user registering on the web application,the function returns
 * true if registering the user was successful otherwise it returns false
 */

if (!function_exists('bRegister'))
{

    function bRegister($sUser, $sPass)
    {
        $error = "";
        $sqlConn = sqlConnect();
        if ($sqlConn === null)
            return false;
        $sUser=  mysql_real_escape_string($sUser);
        $sPass=  mysql_real_escape_string($sPass);
        $sQuery = "INSERT INTO basic (UserName,PassWord)VALUES('{$sUser}','{$sPass}')";
        $rsResult = mysql_query($sQuery, $sqlConn) || $error = mysql_error();
        if ($error === "Duplicate entry '{$sUser}' for key 'PRIMARY'")
        {
            echo"Username already exists";
            mysql_close($sqlConn);
            return false;
        }
        else
        {
            echo"User registered";
            mysql_close($sqlConn);
            return true;
        }
    }

}

/* bMatchPasswords is responsible for checking that the values on the 
 * register new user page in the password and confirm password fields
 * are equal, the function returns true if both passwords are equal otherwise it
 * returns false;
 */

if (!function_exists('bMatchPasswords'))
{

    function bMatchPasswords($sPassword, $sConfirm)
    {
        if ($sPassword === $sConfirm)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}

/* arrSearchByAuthor function searches for every post in the database written by a 
 * specific author having the type plain text
 */

if (!function_exists('rsTextSearchByAuthor'))
{

    function rsTextSearchByAuthor($sAuthor)
    {
        $sqlConn = sqlConnect();
        $sQuery = "SELECT * FROM posts WHERE UserName='{$sAuthor}'";
        $rsResult = mysql_query($sQuery, $sqlConn) or die(mysql_error());
        mysql_close($sqlConn);
        return $rsResult;
    }

}

/* arrSearchByAuthor function searches for every post in the database written by a 
 * specific author having the type Pdf
 */

if (!function_exists('rsPdfSearchByAuthor'))
{

    function rsPdfSearchByAuthor($sAuthor)
    {
        $sqlConn = sqlConnect();
        $sQuery = "SELECT ID,UserName,FileName,FileType,FileSize,Date FROM files WHERE UserName='{$sAuthor}'";
        $rsResult = mysql_query($sQuery, $sqlConn) or die(mysql_error());
        mysql_close($sqlConn);
        return $rsResult;
    }

}

/* blPdf retrieves blob data record from the database with the specific id being $iID
 * and returns it to the calling page
 */

if (!function_exists('rsPdf'))
{

    function rsPdf($iID)
    {
        $sqlConn = sqlConnect();
        $sQuery = "SELECT * FROM files WHERE ID='{$iID}'";
        $rsResult = mysql_query($sQuery, $sqlConn) or die(mysql_error());
        mysql_close($sqlConn);
        return $rsResult;
    }

}

/* arrSearchByDate function searches for every post in the database written by a 
 * specific user having the type plain text
 */

if (!function_exists('rsTextSearchByDate'))
{

    function rsTextSearchByDate($sDate)
    {
        $tsTime = strtotime($sDate);
        $dtDate = date('Y-m-d', $tsTime);
        $sqlConn = sqlConnect();
        $sQuery = "SELECT * FROM posts WHERE Date='{$dtDate}'";
        $rsResult = mysql_query($sQuery, $sqlConn) or die(mysql_error());
        mysql_close($sqlConn);
        return $rsResult;
    }

}

/* arrSearchByDate function searches for every post in the database written by a 
 * specific user having the type Pdf
 */

if (!function_exists('rsPdfSearchByDate'))
{

    function rsPdfSearchByDate($sDate)
    {
        $tsTime = strtotime($sDate);
        $dtDate = date('Y-m-d', $tsTime);
        $sqlConn = sqlConnect();
        $sQuery = "SELECT * FROM files WHERE Date='{$dtDate}'";
        $rsResult = mysql_query($sQuery, $sqlConn) or die(mysql_error());
        mysql_close($sqlConn);
        return $rsResult;
    }

}

/* vDeletePdf deletes the pdf file from the database with the same id $iID
 * the function does not return anything
 */
if (!function_exists('vDeletePdf'))
{

    function vDeletePdf($iID)
    {
        $sqlConn = sqlConnect();
        $sQuery = "DELETE FROM files WHERE ID='{$iID}'";
        $rsResult = mysql_query($sQuery, $sqlConn) or die(mysql_error());
    }

}

/* vDeletePdf deletes the text post from the database with the same id $iID
 * the function does not return anything
 */
if (!function_exists('vDeleteText'))
{

    function vDeleteText($iID)
    {
        $sqlConn = sqlConnect();
        $sQuery = "DELETE FROM posts WHERE ID='{$iID}'";
        $rsResult = mysql_query($sQuery, $sqlConn) or die(mysql_error());
    }

}


/* sqlConnect function attempts to connect to the blog database
 *  and returns a connection object if the connection was successful
 * or null if unsuccessful (N.B. all parameters are optional
 */

if (!function_exists('sqlConnect'))
{

    function sqlConnect($sServer = "localhost", $sServerUser = "root", $sServerPass = "1234")
    {
        $sqlConn = mysql_connect($sServer, $sServerUser, $sServerPass, true) or die(mysql_error());
        mysql_select_db("blog", $sqlConn) or die(mysql_error());
        return $sqlConn;
    }

}

/* vLogout logs out the current user and destorys all stored session data
 * this is a void function it doesnt return anything
 */

if (!function_exists('vLogout'))
{

    function vLogout()
    {
        session_unset();
        session_destroy();
    }

}

/* bAddTextPost adds a post in the database with the poster's name being $sUser
 * it also automatically calculates the current datetime and inserts it with the
 * rest of the information, the function returns true if successful otherwise
 * it returns false
 */

if (!function_exists('bAddTextPost'))
{

    function bAddTextPost($sUser, $sPost)
    {
        $sqlConn = sqlConnect();
        if ($sqlConn === null)
            return false;
        $dtDate = date('Y-m-d');
        $sPost = mysql_real_escape_string($sPost);
        $dtDate = mysql_real_escape_string($dtDate);
        $sUser = mysql_real_escape_string($sUser);
        $sQuery = "INSERT INTO posts(UserName,Post,Date) VALUES('{$sUser}','{$sPost}','{$dtDate}')";
        $rsResult = mysql_query($sQuery, $sqlConn);
        if (!$rsResult)
        {
            die(mysql_error());
            return false;
        }
        mysql_close($sqlConn);
        return true;
    }

}

/* bAddPdfPost adds a pdf file to the database with the poster's name being $sUser
 * and file name being $sName,the file size is supplied through $iSize and the actual
 * binary data is $binData, the function also calculates the date automatically
 */

if (!function_exists('bAddPdfPost'))
{

    function bAddPdfPost($sUser, $sName, $sType, $fFile)
    {
        if (filesize($fFile) < 16000000 && $sType === "application/pdf")
        {
            $sqlConn = sqlConnect();
            if ($sqlConn === null)
                return false;
            $dtDate = date('Y-m-d');
            $fpFile = fopen($fFile, "r");
            $iSize = filesize($fFile);
            $binData = fread($fpFile, $iSize);
            fclose($fpFile);
            $binData = mysql_real_escape_string($binData) or die(mysql_error());
            $sUser = mysql_real_escape_string($sUser);
            $sName = mysql_real_escape_string($sName);
            $sType = mysql_real_escape_string($sType);
            $iSize = mysql_real_escape_string($iSize);
            $dtDate = mysql_real_escape_string($dtDate);
            $sQuery = "INSERT INTO files (UserName,FileName,FileType,FileSize,Date,Data) Values('{$sUser}','{$sName}','{$sType}','{$iSize}','{$dtDate}','{$binData}')";
            $rsResult = mysql_query($sQuery, $sqlConn);
            if (!$rsResult)
            {
                die(mysql_error());
                return false;
            }
            else
            {
                mysql_close($sqlConn);
                return true;
            }
        }
        else
        {
            return false;
        }
    }

}

if (!function_exists('rsText'))
{

    function rsText($iID)
    {
        $sqlConn = sqlConnect();
        $sQuery = "SELECT * FROM posts WHERE ID='{$iID}'";
        $rsResult = mysql_query($sQuery, $sqlConn) or die(mysql_error());
        return $rsResult;
    }

}
?>
